﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;
using System.IO;

namespace VSM.Parts
{
    public partial class ARInvoice : System.Web.UI.Page
    {
        #region Fields
        private GeneralFunctions GF = null;
        private string TblHeaderName = "OINV";
        private string TblLineName = "INV1";
        private string CurrentPageUrl = "/Business/Parts/Sales/ARInvoice.aspx";
        private string HeaderKeyName = "DocEntry";
        private String TargetPageUrl = "/Business/Parts/Sales/IncomingPayment.aspx";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.Private);

            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../../Login.aspx");
            }
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            if (dbType != "VSM")
            {
                this.chkPromotion.Visible = false;
            }
            GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            if (!IsPostBack)
            {
                ClearScreen();
                String invId = Request.QueryString["inv_id"];
                if (!String.IsNullOrEmpty(invId))
                {
                    LoadData(invId, ConvertDocType.Get2String(DocType.AR_INVOICE));
                    if (lblStatus.Text == "Close")
                        SetScreenStatus("Close");
                    else if (lblStatus.Text == "OPen")
                        SetScreenStatus("Update");
                }
                else
                {
                    LoadDefault();
                    SetScreenStatus("New");
                }

                String BaseEntry = Request.QueryString["base_entry"];
                if (!String.IsNullOrEmpty(BaseEntry))
                {
                    String BaseType = Request.QueryString["base_type"];
                    LoadData(BaseEntry, BaseType);
                }
            }
        }

        private void LoadConfig()
        {
            //Load Config
            MasterData obj = new MasterData();
            DataSet dsConfig = obj.GetConfig("VSM", Session[Utils.AppConstants.ID_Dealer].ToString());
            if (dsConfig != null && dsConfig.Tables.Count > 0 && dsConfig.Tables[0].Rows.Count > 0)
            {
                this.txtKH.Text = dsConfig.Tables[0].Rows[0]["Series"].ToString();
                this.hdnConfigID.Value = dsConfig.Tables[0].Rows[0]["ID"].ToString();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvINV.PageIndex = e.NewPageIndex;
            DataTable tblINV = (DataTable)Session["INVTable"];
            BindData(tblINV);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");

                DataTable tbINV = (DataTable)Session["INVTable"];
                if (tbINV != null)
                {
                    DataRow[] rupdate = tbINV.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tbINV.Rows.Remove(rupdate[0]);
                    }
                    this.grvINV.EditIndex = -1;
                    BindData((DataTable)Session["INVTable"]);
                    CalcTotal(((DataTable)Session["INVTable"]));
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Price');", true);
                    txtUnitPrice.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["INVTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["PriceBefDi"] = txtUnitPrice.Text;
                        updateRowTotalPrice(rupdate[0], "PriceBefDi");
                    }
                }

                this.grvINV.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
      
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtDiscount_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscount = (TextBox)row.FindControl("txtDiscount");
                if (txtDiscount.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Discount');", true);
                    txtDiscount.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["INVTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DiscPrcnt"] = txtDiscount.Text;
                        updateRowTotalPrice(rupdate[0], "DiscPrcnt");
                    }
                }

                this.grvINV.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["INVTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        updateRowTotalPrice(rupdate[0], "Quantity");
                    }
                }

                this.grvINV.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dr"></param>
        private DataRow FillShipToAddress(string outletId, bool isFill)
        {
            try
            {
                if (outletId.Length > 0)
                {
                    MasterData obj = new MasterData();
                    DataSet tbWareHouse = null;//obj.GetWareHouseAddress(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode);
                    if (tbWareHouse != null && tbWareHouse.Tables.Count > 0)
                    {

                        DataRow[] r = tbWareHouse.Tables[0].Select("WhsCode = '" + outletId + "'");
                        if (r.Length > 0)
                        {
                            if (isFill)
                            {
                                StringBuilder shipTo = new StringBuilder();
                                shipTo.AppendLine(r[0]["Block"].ToString());
                                shipTo.AppendLine(r[0]["Street"].ToString() + " " + r[0]["City"].ToString());
                                shipTo.AppendLine(r[0]["Country"].ToString() + " " + r[0]["ZipCode"].ToString());
                            }
                            else
                            {
                                return r[0];
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                e.Cancel = true;
                GridViewRow row = (GridViewRow)this.grvINV.Rows[e.RowIndex];
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["INVTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvINV.EditIndex = -1;
                    BindData((DataTable)Session["INVTable"]);
                    CalcTotal(((DataTable)Session["INVTable"]));
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {

            Session["INVTable"] = tblData;
            this.grvINV.DataSource = tblData;
            this.grvINV.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime invDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataTable tblINV = (DataTable)Session["INVTable"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblINV != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    MasterData obj = new MasterData();
                                    string lstItemCode = string.Empty;

                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        if (string.IsNullOrEmpty(lstItemCode)) lstItemCode = "'" + item.Key + "'";
                                        else lstItemCode = lstItemCode + ", '" + item.Key + "'";
                                    }

                                    DataSet dsItem = obj.GetItemsByItemCodeList(dbType, Utils.AppConstants.ID_Dealer, lstItemCode);
                                    GetDefault defaultWS = new GetDefault();

                                    if (dsItem != null && dsItem.Tables.Count > 0)
                                    {
                                        foreach (DataRow dr in dsItem.Tables[0].Rows)
                                        {
                                            LoadItem(invDate, ref tblINV, dbType, dr["ItemCode"].ToString(), "1", "0", "");
                                        }
                                    }
                                    if (tblINV.Rows.Count > 0)
                                    {
                                        //Update Price
                                        foreach (DataRow dr in tblINV.Rows)
                                        {
                                            updateRowTotalPrice(dr, "");
                                        }
                                        CalcTotal(tblINV);
                                    }
                                }
                            }
                            //ReLoad Data
                            BindData(tblINV);
                            break;

                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            GridViewRow row = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;

                            this.txtCustomerCode.Text = ((Label)row.FindControl("lblCardCode")).Text;
                            this.txtCustomerName.Text = ((Label)row.FindControl("lblCardName")).Text;
                            this.txtContactPerson.Text = ((Label)row.FindControl("lblCntctPrsn")).Text;

                            if (tblINV != null) tblINV.Rows.Clear();
                            Session["ChosenBP"] = null;
                            this.FileUploadControl.Enabled = true;
                            this.btnImport.Enabled = true;
                            this.btnAddItems.Enabled = true;
                            this.txtItemCode.Enabled = true;
                            this.btnCopyFromDO.Enabled = true;
                            this.btnCopyFromSO.Enabled = true;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string soId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            ClearScreen();
                            LoadData(soId, doctype);
                            break;
                        case "ChosenDODocList":
                            Dictionary<string, GridViewRow> dicDOItem = new Dictionary<string, GridViewRow>();
                            dicDOItem = Session["ChosenDODocList"] != null ? (Dictionary<string, GridViewRow>)Session["ChosenDODocList"] : null;
                            //Count SO
                            Session["SOCount"] = 0;
                            if (dicDOItem != null)
                            {
                                int i = 0;
                                foreach (KeyValuePair<string, GridViewRow> DOitem in dicDOItem)
                                {
                                    Session["SOCount"] = i;
                                    GridViewRow rowDODocList = DOitem.Value;
                                    string DOId = ((Label)rowDODocList.FindControl("lblDocNum")).Text;
                                    string DOdoctype = ((Label)rowDODocList.FindControl("lblDocType")).Text;
                                    LoadData(DOId, DOdoctype);
                                    i++;
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="tblIPO"></param>
        /// <returns></returns>
        private DataTable LoadSetupItem(DateTime poDate, DataTable tblIPO)
        {
            MasterData obj = new MasterData();
            DataSet dsItem = null;
            Dictionary<string, string> dicItem = new Dictionary<string, string>();
            if (dsItem != null && dsItem.Tables.Count > 0)
            {
                dsItem.Tables[0].Columns.Add("Quantity");
                DataSet dsAllPrice = null;
                foreach (DataRow r in dsItem.Tables[0].Rows)
                {
                    if (!dicItem.ContainsKey(r["ItemCode"].ToString()))
                    {
                        dicItem.Add(r["ItemCode"].ToString(), r["ItemName"].ToString());
                    }
                    if (dsAllPrice != null && dsAllPrice.Tables.Count > 0)
                    {
                        foreach (DataRow row in dsAllPrice.Tables[0].Rows)
                        {
                            if (r["ItemCode"].ToString() == row["ItemCode"].ToString())
                            {
                                DataRow rowNew = tblIPO.NewRow();
                                rowNew["ItemCode"] = r["ItemCode"].ToString();
                                rowNew["Dscription"] = r["ItemName"].ToString();
                                rowNew["LB"] = r["LB"].ToString();
                                rowNew["MinStock"] = Math.Round(decimal.Parse(r["MinQty"].ToString()), 2);
                                rowNew["MaxStock"] = Math.Round(decimal.Parse(r["MaxQty"].ToString()), 2);
                                rowNew["BuyUnitMsr"] = row["BuyUnitMsr"];
                                rowNew["Quantity"] = decimal.Parse("0").ToString("#,##0.00");
                                rowNew["ReceivedQty"] = row["ReceivedQty"];
                                if (row["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                                {
                                    rowNew["Price"] = (decimal.Parse(row["NumInBuy"].ToString()) * decimal.Parse(row["Price"].ToString())).ToString("#,##0.00");
                                }
                                else
                                {
                                    rowNew["Price"] = decimal.Parse(row["Price"].ToString()).ToString("#,##0.00");
                                }
                                rowNew["LineTotal"] = decimal.Parse(row["LineTotal"].ToString()).ToString("#,##0.00");
                                rowNew["VatgroupPu"] = row["VatgroupPu"];
                                rowNew["Rate"] = row["Rate"];
                                rowNew["ShipType"] = row["ShipType"];
                                rowNew["TrnspName"] = row["TrnspName"];
                                DataRow[] rCheck = tblIPO.Select("ItemCode='" + r["ItemCode"].ToString() + "'");
                                if (rCheck.Length == 0)
                                {
                                    tblIPO.Rows.Add(rowNew);
                                }
                            }
                        }
                    }
                }
            }
            Session["ChosenItem"] = dicItem;
            //ReLoad Data
            BindData(tblIPO);
            if (tblIPO.Rows.Count > 0)
            {
                CalcTotal(tblIPO);
            }
            this.btnSave.Enabled = true;
            this.FileUploadControl.Enabled = true;
            this.btnImport.Enabled = true;
            this.btnAddItems.Enabled = true;
            return tblIPO;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="tblINV"></param>
        /// <param name="dbType"></param>
        /// <param name="key"></param>
        /// <param name="quantity"></param>
        /// <param name="discount"></param>
        /// <param name="price"></param>
        private void LoadItem(DateTime poDate, ref DataTable tblINV, string dbType, string key, string quantity, string discount, string price)
        {
            GetDefault defaultWS = new GetDefault();

            DataSet defaultInfo = null;
            try
            {
                defaultInfo = defaultWS.GetPartsDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                    this.txtCustomerCode.Text, key, 1, poDate, Utils.AppConstants.PARTS, "2");
            }
            catch
            {
            }
            if (defaultInfo != null)
            {

                DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);
                DataTable dtVatGroup = GF.GetVatGroupByCategory(dbType, "O");
                DataRow rowNew = tblINV.NewRow();
                rowNew["No"] = (tblINV.Rows.Count + 1).ToString();
                rowNew["ItemCode"] = key;
                rowNew["Dscription"] = defaultInfo.Tables[0].Rows[0]["ItemName"];
                rowNew["U_Model"] = defaultInfo.Tables[0].Rows[0]["U_Model"];
                rowNew["unitMsr"] = defaultInfo.Tables[0].Rows[0]["UomCode"];
                rowNew["Quantity"] = quantity;
                if (discount.Length > 0)
                {
                    rowNew["DiscPrcnt"] = discount;
                }
                else
                {
                    rowNew["DiscPrcnt"] = 0;
                }
                if (price.Length == 0)
                {
                    if (defaultInfo != null && defaultInfo.Tables.Count > 0 && defaultInfo.Tables[0].Rows.Count > 0)
                    {
                        rowNew["PriceBefDi"] = defaultInfo.Tables[0].Rows[0]["UnitPrice"];
                    }
                    else
                    {
                        rowNew["PriceBefDi"] = 0;
                    }
                }
                else
                {
                    rowNew["PriceBefDi"] = price;
                }
                if (this.chkPromotion.Checked == false)
                {
                    rowNew["U_PromotionPrice"] = 0;
                }
                else
                {
                    rowNew["U_PromotionPrice"] = rowNew["PriceBefDi"];
                }
                rowNew["VatPrcnt"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Rate"].ToString() : "0";
                rowNew["U_Discount"] =
                rowNew["TaxCode"] = defaultInfo.Tables[0].Rows[0]["TaxCode"].ToString();
                rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;

                DataRow[] rExist = tblINV.Select("ItemCode='" + key + "'");
                if (rExist.Length == 0)
                {
                    tblINV.Rows.Add(rowNew);
                }
                if (chkPromotion.Checked)
                {
                    this.grvINV.Columns[7].Visible = false;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblIPO"></param>
        /// <param name="drDefaultLine"></param>
        /// <param name="itemCode"></param>
        /// <param name="itemName"></param>
        /// <param name="Model"></param>
        /// <param name="Color"></param>
        /// <returns></returns>
        private DataTable AddNewItem(DataTable tblINV, DataRow drDefaultLine, string ItemCode, string Dscription, string Model, string Color, string uom)
        {
            try
            {
                if (drDefaultLine != null && drDefaultLine.ItemArray.Length > 0)
                {
                    DataRow rowNew = tblINV.NewRow();
                    rowNew["No"] = (tblINV.Rows.Count + 1).ToString();
                    rowNew["ItemCode"] = ItemCode;
                    rowNew["Dscription"] = Dscription;
                    rowNew["U_Model"] = Model;
                    rowNew["U_Color"] = Color;
                    rowNew["Quantity"] = 1;
                    rowNew["unitMsr"] = uom;
                    rowNew["PriceBefDi"] = drDefaultLine["UnitPrice"];
                    rowNew["DiscPrcnt"] = drDefaultLine["Discount"];
                    rowNew["PriceBefDi"] = drDefaultLine["PriceAfDi"];

                    rowNew["TaxCode"] = drDefaultLine["TaxCode"];
                    rowNew["VatPrcnt"] = drDefaultLine["TaxRate"];
                    rowNew["WhsCode"] = drDefaultLine["WhsCode"];

                    DataRow[] rCheck = tblINV.Select("ItemCode='" + ItemCode + "'");
                    if (rCheck.Length == 0)
                    {
                        tblINV.Rows.Add(rowNew);
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return tblINV;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void CalcTotal(DataTable tb)
        {
            try
            {
                double documentTotal = 0;
                double gstTotal = 0;
                double subTotal = 0;
                foreach (DataRow row in tb.Rows)
                {
                    subTotal += double.Parse(row["LineTotal"].ToString());
                    if (row["Rate"] != null && row["Rate"].ToString().Length > 0)
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * double.Parse(row["Rate"].ToString())) / 100;
                    }
                    else
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * 8.25) / 100;
                    }
                }
                documentTotal += subTotal + gstTotal;

                this.lblSubTotal.Text = GF.FormatNumeric(subTotal.ToString(), "SumDec");
                this.lblTaxAmount.Text = GF.FormatNumeric(gstTotal.ToString(), "SumDec");
                this.lblPaymentTotal.Text = GF.FormatNumeric(documentTotal.ToString(), "SumDec");
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private DataSet GetDataItem(DateTime poDate, string itemCode, string venderCode, double quantity)
        {
            try
            {
                MasterData obj = new MasterData();
                DataSet ds = new DataSet();
                ds = null;
                return ds;
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {

            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }



        public String _collectData()
        {
            try
            {
                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("DocNum");
                if (!hdnIsUpdate.Value.Equals("true"))
                {
                    dtHeader.Columns.Add("Series"); // 4
                    dtHeader.Columns.Add("DocStatus");
                }
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("NumAtCard");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("CtlAccount");
              
                //UDF
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");
                dtHeader.Columns.Add("U_Pkyhieu");
                if (Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM")
                {
                    dtHeader.Columns.Add("U_Issue");
                }
                DataRow drHeader = dtHeader.NewRow();
                if (hdnIsUpdate.Value.Equals("true"))
                {
                    drHeader["DocEntry"] =
                    drHeader["DocNum"] = int.Parse(txtDocNo.Text);
                }
                else
                {
                    drHeader["Series"] = 4;
                    drHeader["DocStatus"] = "O";
                }

                if (Utils.AppConstants.isDateTime(this.txtPostingDate.Text))
                {
                    drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                }
                if (Utils.AppConstants.isDateTime(this.txtDueDate.Text))
                {
                    drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(txtDueDate.Text).ToString("yyyyMMdd");
                }
                if (Utils.AppConstants.isDateTime(this.txtDocDate.Text))
                {
                    drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                }

                drHeader["Comments"] = txtRemarks.Text.Trim();
                drHeader["CardCode"] = txtCustomerCode.Text;
                drHeader["CardName"] = txtCustomerName.Text.Trim();
                drHeader["NumAtCard"] = txtInvNo.Text.Trim();
                drHeader["CtlAccount"] = "1311-10";
                //UDF
                drHeader["U_ContactPerson"] = txtContactPerson.Text.Trim();
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.PARTS;
                drHeader["U_Pkyhieu"] = this.txtKH.Text;
                if (Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM")
                {
                    if (this.chkPromotion.Checked)
                    {
                        drHeader["U_Issue"] = "KM";
                    }
                    else
                    {
                        drHeader["U_Issue"] = "XB";
                    }
                }

                dtHeader.Rows.Add(drHeader);

                Array arrContentsCols = new string[] { "Quantity", "PriceBefDi", "Price", "DiscPrcnt", "LineTotal" }; // Columns need to reset format numeric


                DataSet ds = new DataSet("DS");
                dtHeader.TableName = TblHeaderName;
                DataTable dtContents = (DataTable)Session["INVTable"];

                dtContents.TableName = TblLineName;
                ds.Tables.Add(dtHeader.Copy());

                DataTable dt = new DataTable(TblLineName);
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("LineStatus");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("Price");
                dt.Columns.Add("DiscPrcnt");
                dt.Columns.Add("unitMsr");
                dt.Columns.Add("LineTotal");
                dt.Columns.Add("PriceBefDi");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Discount");
                dt.Columns.Add("U_PromotionPrice");
                if (Session["SOCount"] == null || ((int)Session["SOCount"]) == 0)
                {
                    if (!this.hdnIsUpdate.Value.Equals("true"))
                    {
                        if (!String.IsNullOrEmpty(hdnBaseType.Value))
                        {
                            dt.Columns.Add("BaseEntry");
                            dt.Columns.Add("BaseLine");
                            dt.Columns.Add("BaseType");
                        }
                    }
                }
                int liNo = 0;
                foreach (DataRow dr in dtContents.Rows)
                {
                    DataRow rowNew = dt.NewRow();
                    if (hdnIsUpdate.Value.Equals("true")) rowNew["DocEntry"] = int.Parse(txtDocNo.Text);
                    rowNew["LineNum"] = liNo;
                    rowNew["LineStatus"] = "O";
                    rowNew["ItemCode"] = dr["ItemCode"];
                    rowNew["Dscription"] = dr["Dscription"];
                    rowNew["Quantity"] = dr["Quantity"];
                    rowNew["Price"] = dr["Price"];
                    rowNew["unitMsr"] = dr["unitMsr"];
                    rowNew["DiscPrcnt"] = dr["DiscPrcnt"];
                    rowNew["LineTotal"] = dr["LineTotal"];
                    rowNew["PriceBefDi"] = dr["PriceBefDi"];
                    rowNew["U_Color"] = dr["U_Color"];
                    rowNew["U_Model"] = dr["U_Model"];
                    rowNew["U_Discount"] = dr["U_Discount"];
                    rowNew["U_PromotionPrice"] = dr["U_PromotionPrice"];
                    if (Session["SOCount"] == null || ((int)Session["SOCount"]) == 0)
                    {
                        if (!this.hdnIsUpdate.Value.Equals("true"))
                        {
                            if (!String.IsNullOrEmpty(hdnBaseType.Value))
                            {
                                rowNew["BaseEntry"] = dr["BaseEntry"];
                                rowNew["BaseLine"] = dr["BaseLine"];
                                rowNew["BaseType"] = dr["BaseType"];
                            }
                        }
                    }

                    dt.Rows.Add(rowNew);
                    liNo++;
                }

                ds.Tables.Add(GF.ResetFormatNumeric(dt, arrContentsCols).Copy());
                DocumentXML objInfo = new DocumentXML();
                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.AR_INVOICE), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();
                if (this.hdnStatus.Value == "C")
                {
                    this.ddlPaymentMeans.Enabled = false;
                    this.txtKH.Enabled = false;
                    this.txtDocDate.Enabled = false;
                    this.txtDueDate.Enabled = false;
                    this.txtInvNo.Enabled = false;
                    this.txtPostingDate.Enabled = false;
                    this.txtContactPerson.Enabled = false;
                    this.ddlSaleMan.Enabled = false;
                    this.txtRemarks.Enabled = false;

                    TextBox txtQuantity = (TextBox)myRow.FindControl("txtOrderQuantity");
                    TextBox txtUnitPrice = (TextBox)myRow.FindControl("txtUnitPrice");
                    TextBox txtDiscount = (TextBox)myRow.FindControl("txtDiscount");
                    TextBox txtPromotionPrice = (TextBox)myRow.FindControl("txtPromotionPrice");

                    if (txtQuantity != null)
                    {
                        txtQuantity.ReadOnly = true;
                        txtQuantity.BorderStyle = BorderStyle.None;
                        txtQuantity.BackColor = System.Drawing.Color.Transparent;
                    }
                    if (txtUnitPrice != null)
                    {
                        txtUnitPrice.ReadOnly = true;
                        txtUnitPrice.BorderStyle = BorderStyle.None;
                        txtUnitPrice.BackColor = System.Drawing.Color.Transparent;
                    }
                    if (txtDiscount != null)
                    {
                        txtDiscount.ReadOnly = true;
                        txtDiscount.BorderStyle = BorderStyle.None;
                        txtDiscount.BackColor = System.Drawing.Color.Transparent;
                    }
                    if (txtPromotionPrice != null)
                    {
                        txtPromotionPrice.ReadOnly = true;
                        txtPromotionPrice.BorderStyle = BorderStyle.None;
                        txtPromotionPrice.BackColor = System.Drawing.Color.Transparent;
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
                this.FileUploadControl.Enabled = true;
                this.btnImport.Enabled = true;
                this.btnAddItems.Enabled = true;
            }
            catch
            {
                this.FileUploadControl.Enabled = false;
                this.btnImport.Enabled = false;
                this.btnAddItems.Enabled = false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                if (this.txtDueDate.Text.Length == 0)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Pls. Select DocDueDate." + "','');", true);
                    return;
                }
                if (string.IsNullOrEmpty(this.txtKH.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Series.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtKH.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtInvNo.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Invoice No.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtInvNo.Focus();
                    return;
                }
                else
                {
                    if (!hdnIsUpdate.Value.Equals("true"))
                    {
                        string lsNumAtCard = GF.GetSingleValue(dbType, " select NumAtCard from OINV where NumAtCard = '" + txtInvNo.Text.Trim() + "'", "NumAtCard");
                        string U_Pkyhieu = GF.GetSingleValue(dbType, " select U_Pkyhieu from OINV where U_Pkyhieu = '" + txtKH.Text.Trim() + "'", "U_Pkyhieu");
                        if (!string.IsNullOrEmpty(lsNumAtCard) && !string.IsNullOrEmpty(U_Pkyhieu))
                        {
                            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('The Series existed.','');", true);
                            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                            txtInvNo.Focus();
                            return;
                        }
                    }
                }
                String requestXML = _collectData();
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, ((ulong)DocType.AR_INVOICE).ToString(), txtDocNo.Text, hdnIsUpdate.Value.Equals("true"), dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    //Update Config
                    DataTable dt = new DataTable("U_Config");
                    dt.Columns.Add("ID");
                    dt.Columns.Add("CardCode");
                    dt.Columns.Add("Series");
                    DataRow dr = dt.NewRow();
                    dr["ID"] = this.hdnConfigID.Value;
                    dr["CardCode"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                    dr["Series"] = this.txtKH.Text;
                    dt.Rows.Add(dr);
                    DocumentXML objInfo = new DocumentXML();
                    DataSet dsConfig = new DataSet("DS");
                    dt.TableName = "U_Config";
                    dsConfig.Tables.Add(dt.Copy());
                    MasterData obj = new MasterData();
                    obj.UpdateSeriesConfig(dsConfig, "VSM");

                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dtContent"></param>
        /// <returns></returns>
        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("PriceBefDi");
            dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("unitMsr");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("LineTotal");

            dt.Columns.Add("SysNumber");
            dt.Columns.Add("DistNumber");
            dt.Columns.Add("InDate");
            dt.Columns.Add("Notes");

            dt.Columns.Add("TaxCode");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("Rate");
            dt.Columns.Add("WhsCode");
            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("BaseType");
            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");
            dt.Columns.Add("U_Discount");
            dt.Columns.Add("U_PromotionPrice");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();
                    row["No"] = dr["No"];
                    row["ItemCode"] = dr["ItemCode"];
                    row["Dscription"] = dr["Dscription"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Color"] = dr["U_Color"];
                    row["PriceBefDi"] = dr["PriceBefDi"];
                    row["DiscPrcnt"] = dr["DiscPrcnt"];
                    row["Price"] = dr["Price"];
                    row["unitMsr"] = dr["unitMsr"];
                    row["Quantity"] = dr["OpenQty"];
                    row["LineTotal"] = dr["LineTotal"];

                    if (dr.Table.Columns.Contains("DistNumber"))
                    {
                        row["SysNumber"] = dr["SysNumber"];
                        row["DistNumber"] = dr["DistNumber"];
                        row["InDate"] = dr["InDate"];
                        row["Notes"] = dr["Notes"];
                    }
                    row["VatPrcnt"] = dr["VatPrcnt"];
                    row["Rate"] = dr["Rate"];
                    row["WhsCode"] = dr["WhsCode"];
                    row["DocEntry"] = dr["DocEntry"];
                    row["LineNum"] = dr["LineNum"];
                    row["BaseType"] = dr["BaseType"];
                    row["BaseEntry"] = dr["BaseEntry"];
                    row["BaseLine"] = dr["BaseLine"];
                    row["U_Discount"] = dr["U_Discount"];
                    row["U_PromotionPrice"] = dr["U_PromotionPrice"];
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="invId"></param>
        /// <param name="NewDocType"></param>
        protected void LoadData(String invId, string NewDocType)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();
            DataSet returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, invId, dbType);
            DataTable dtHeader = new DataTable();
            if (returnDoc == null)
            {
                invId = "1";
                returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, invId, dbType);
                if (returnDoc != null || returnDoc.Tables.Count >= 2)
                    dtHeader = returnDoc.Tables[0];
            }
            else dtHeader = returnDoc.Tables[0];

            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }


            DataRow dr = dtHeader.Rows[0];
            if (dtHeader.Columns.Contains("U_Issue"))
            {
                if (dr["U_Issue"].ToString() == "KM")
                {
                    this.chkPromotion.Checked = true;
                    this.grvINV.Columns[7].Visible = false;
                }
            }
            else
            {
                this.grvINV.Columns[8].Visible = false;
            }
            this.txtDocNo.Text = dr["DocNum"].ToString();
            this.txtCustomerCode.Text = dr["CardCode"].ToString();
            this.txtCustomerName.Text = dr["CardName"].ToString();
            if (dtHeader.Columns.Contains("U_Pkyhieu"))
            {
                this.txtKH.Text = dr["U_Pkyhieu"].ToString();
            }
            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            txtDueDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDueDate"], new CultureInfo("es-US")));

            txtContactPerson.Text = dr["U_ContactPerson"].ToString();
            if (NewDocType != "15")
             {
                 txtInvNo.Text = dr["NumAtCard"].ToString();
             }
            txtRemarks.Text = dr["Comments"].ToString();

            // Binding Data Sale Man
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlSaleMan, dr["SlpCode"].ToString());

            if (dr["DocStatus"].ToString().Equals("C"))
            {
                this.lblStatus.Text = "Closed";
                SetScreenStatus("Close");
            }
            else if (dr["DocStatus"].ToString().Equals("O"))
            {
                this.lblStatus.Text = "Open";
                if (NewDocType != ConvertDocType.Get2String(DocType.AR_INVOICE))
                    SetScreenStatus("New");
                else SetScreenStatus("Update");
            }

            DataTable dtContents = BuildContents(returnDoc.Tables[1]);
            hdnBaseType.Value = NewDocType;

            if (ConvertDocType.Get2String(DocType.AR_INVOICE) != NewDocType) //In this case: copy from Sales Order
            {
                foreach (DataRow row in dtContents.Rows)
                {
                    updateRowTotalPrice(row, "");
                    row["BaseEntry"] = invId;
                    row["BaseType"] = NewDocType;
                    row["BaseLine"] = row["LineNum"];
                }
            }
            else
            {
                foreach (DataRow row in dtContents.Rows)
                {
                    updateRowTotalPrice(row, "");
                    row["InDate"] = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(row["InDate"], new CultureInfo("es-US")));
                }
            }
            DataTable tb = null;
            tb = (DataTable)Session["INVTable"];
            if (tb != null)
            {
                foreach (DataRow r in dtContents.Rows)
                {
                    r["No"] = tb.Rows.Count + 1;
                    tb.ImportRow(r);
                }
            }
            else
            {
                tb = dtContents;
            }
            BindData(tb);
            updateTableTotalPrice();
            if (this.txtKH.Text.Length == 0)
            {
                LoadConfig();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        protected void LoadDefault()
        {

            this.lblStatus.Text = "Open";
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDueDate.Text = string.Empty;
            this.txtDocDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDocNo.Text =
            this.txtCustomerCode.Text =
            this.txtCustomerName.Text =
            this.txtContactPerson.Text =
            this.txtInvNo.Text =
            this.txtRemarks.Text =
            hdnBaseType.Value = string.Empty;

            // Binding Data Sale Man
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlSaleMan, "-1");

            DataTable dtContents = BuildContents(null);
            BindData(dtContents);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="row"></param>
        /// <param name="Flag"></param>
        public void updateRowTotalPrice(DataRow row, string Flag)
        {
            try
            {
                double quantity = 0, unitPrice = 0.0, discount = 0, priceAfterDiscount = 0.0, total = 0, promotionPrice;
                quantity = GF.Object2Double(GF.ResetFormatNumeric(row["Quantity"].ToString()), "QtyDec");
                unitPrice = GF.Object2Double(GF.ResetFormatNumeric(row["PriceBefDi"].ToString()), "PriceDec");
                promotionPrice = GF.Object2Double(GF.ResetFormatNumeric(row["U_PromotionPrice"].ToString()), "PriceDec");
                discount = GF.Object2Double(GF.ResetFormatNumeric(row["DiscPrcnt"].ToString()), "PercentDec");

                priceAfterDiscount = GF.Object2Double((Object)(unitPrice * (100 - discount) / 100), "PriceDec");
                total = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");

                if (string.IsNullOrEmpty(Flag))
                {
                    row["PriceBefDi"] = GF.FormatNumeric(unitPrice.ToString(), "PriceDec");
                }
                if (string.IsNullOrEmpty(Flag) || Flag.Equals("PriceBefDi") || Flag.Equals("DiscPrcnt"))
                {
                    row["DiscPrcnt"] = GF.FormatNumeric(discount.ToString(), "PercentDec");
                }
                row["Price"] = GF.FormatNumeric(priceAfterDiscount.ToString(), "PriceDec");
                row["LineTotal"] = GF.FormatNumeric(total.ToString(), "SumDec");
                if (string.IsNullOrEmpty(Flag) || Flag.Equals("PriceBefDi") || Flag.Equals("DiscPrcnt") || Flag.Equals("Quantity"))
                {
                    row["Quantity"] = GF.FormatNumeric(quantity.ToString(), "QtyDec");
                }
                row["U_PromotionPrice"] = GF.FormatNumeric(promotionPrice.ToString(), "PriceDec");
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }
        /// <summary>
        /// 
        /// </summary>
        protected void updateTableTotalPrice()
        {
            double orderTotalBeforeDiscount = 0.0;
            double orderTotal = 0.0;
            double taxTotal = 0.0;
            DataTable dtContents = (DataTable)Session["INVTable"];
            foreach (DataRow row in dtContents.Rows)
            {
                if (!"".Equals(row["ItemCode"]))
                {
                    double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["LineTotal"].ToString()), "SumDec");
                    double taxRate = GF.Object2Double(row["VatPrcnt"], "RateDec");
                    if (taxRate == 0) taxRate = 10;
                    double tax = total * taxRate / 100;
                    orderTotalBeforeDiscount += total;
                    taxTotal += tax;
                }
            }
            this.lblSubTotal.Text = GF.FormatNumeric(orderTotalBeforeDiscount.ToString(), "SumDec");
            this.lblTaxAmount.Text = GF.FormatNumeric(taxTotal.ToString(), "SumDec");
            orderTotal = orderTotalBeforeDiscount + taxTotal;
            this.lblPaymentTotal.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
        }
        /// <summary>
        /// 
        /// </summary>
        protected void ClearScreen()
        {
            DataTable dtHeader = new DataTable(TblHeaderName);

            dtHeader.Columns.Add("Series");
            dtHeader.Columns.Add("DocStatus");
            dtHeader.Columns.Add("DocDate");
            dtHeader.Columns.Add("DocDueDate");
            dtHeader.Columns.Add("TaxDate");
            dtHeader.Columns.Add("CardCode");
            dtHeader.Columns.Add("CardName");
            dtHeader.Columns.Add("U_ContactPerson");
            dtHeader.Columns.Add("Comments");
            // Binding Data Sale Man
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlSaleMan, "-1");
            dtHeader.Rows.Add();

            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);
            txtDueDate.Text.ToString(ci);
            txtDocDate.Text.ToString(ci);
            txtCustomerCode.Text =
            txtCustomerName.Text =
            txtRemarks.Text =
            txtContactPerson.Text =
            this.txtDocNo.Text =
            this.txtInvNo.Text =
            this.txtBillTo.Text =
            this.txtKH.Text =
            this.lblPaymentTotal.Text =
            this.lblSubTotal.Text =
            this.lblTaxAmount.Text =
            this.lblDiscount.Text =
            hdnBaseType.Value = String.Empty;
            this.chkPromotion.Checked = false;
            this.btnCopyFromDO.Enabled = false;
            this.btnDocList.Enabled = true;

            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("PriceBefDi");
            dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("LineTotal");
            dt.Columns.Add("unitMsr");
            dt.Columns.Add("SysNumber");
            dt.Columns.Add("DistNumber");
            dt.Columns.Add("InDate");
            dt.Columns.Add("Notes");
            dt.Columns.Add("TaxCode");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("Rate");
            dt.Columns.Add("WhsCode");
            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("BaseType");
            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");
            dt.Columns.Add("U_Discount");
            dt.Columns.Add("U_PromotionPrice");
            BindData(dt);
            SetScreenStatus("New");
            LoadConfig();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Status"></param>
        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    this.txtItemCode.Enabled =
                            this.FileUploadControl.Enabled = false;
                    this.btnImport.Enabled = false;
                    btnAddItems.Enabled = false;
                    btnSave.Visible = true;
                    btnCancel.Visible = true;
                    hdnIsUpdate.Value = "false";
                    this.hdnStatus.Value = "O";
                    break;

                case "Update":
                    this.FileUploadControl.Enabled = true;
                    this.btnImport.Enabled = true;
                    this.txtItemCode.Enabled =
                    btnAddItems.Enabled = true;
                    btnSave.Visible = true;
                    btnCancel.Visible = true;
                    hdnIsUpdate.Value = "true";
                    this.hdnStatus.Value = "O";
                    break;

                case "Close":
                    this.txtItemCode.Enabled =
                    this.FileUploadControl.Enabled = false;
                    this.btnImport.Enabled = false;
                    btnAddItems.Enabled = false;
                    btnSave.Visible = false;
                    btnCancel.Visible = true;
                    this.hdnStatus.Value = "C";
                    this.btnSelectCustomer.Enabled = false;
                    break;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkOSRI_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow gr = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)gr.FindControl("lblItemCode");
                Label lblWhsCode = (Label)gr.FindControl("lblWhsCode");
                string popup = "OpenOSRI('" + lblItemCode.Text + "','" + "01" + "')";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", popup, true);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsDocNo = fGetDefault.GetMaxDocEntry(
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER,
                Session[Utils.AppConstants.ID_Dealer].ToString(),
                Utils.AppConstants.PARTS,
                ConvertDocType.Get2String(DocType.AR_INVOICE),
                TblHeaderName, HeaderKeyName
            );
            if (txtDocNo.Text.CompareTo(lsDocNo) != 0) Response.Redirect(CurrentPageUrl + "?inv_id=" + lsDocNo);
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            ClearScreen();
        }

        protected void chkPromotion_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < this.grvINV.Rows.Count; i++)
            {

                Label lblItemCode = (Label)this.grvINV.Rows[i].FindControl("lblItemCode");
                TextBox txtUnitPrice = (TextBox)this.grvINV.Rows[i].FindControl("txtUnitPrice");
                TextBox txtPromotionPrice = (TextBox)this.grvINV.Rows[i].FindControl("txtPromotionPrice");
                DataTable tb = (DataTable)Session["INVTable"];
                if (tb != null)
                {
                    DataRow[] r = tb.Select("ItemCode = '" + lblItemCode.Text + "'");
                    if (r.Length > 0)
                    {
                        if (this.chkPromotion.Checked)
                        {
                            this.grvINV.Columns[7].Visible = false;
                            r[0]["U_PromotionPrice"] = txtUnitPrice.Text;
                            txtPromotionPrice.Text = txtUnitPrice.Text;
                        }
                        else
                        {
                            this.grvINV.Columns[7].Visible = true;
                            r[0]["U_PromotionPrice"] = 0;
                            txtPromotionPrice.Text = "0";
                        }
                    }
                }
            }
        }

        protected void txtItemCode_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string priceType = string.Empty;
                DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                DataTable tblRDR1 = (DataTable)Session["INVTable"];
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                LoadItem(poDate, ref tblRDR1, dbType, this.txtItemCode.Text.Trim(), "1", "0", "");

                if (tblRDR1.Rows.Count > 0)
                {
                    foreach (DataRow dr in tblRDR1.Rows)
                    {
                        updateRowTotalPrice(dr, "");
                    }
                }

                BindData(tblRDR1);
                updateTableTotalPrice();
                this.txtItemCode.Text = "";
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPromtionPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtPromotionPrice = (TextBox)row.FindControl("txtPromotionPrice");
                if (txtPromotionPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Price');", true);
                    txtPromotionPrice.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["INVTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["U_PromotionPrice"] = GF.FormatNumeric(txtPromotionPrice.Text, "PriceDec");
                    }
                }

                BindData(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        private bool ImportValidation()
        {
            if (this.FileUploadControl.PostedFile == null && this.FileUploadControl.PostedFile.FileName.Length <= 0)
            {
                Session["errorMessage"] = "Please select a Excel file before click on Import button.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            string lsFileExtension = Path.GetExtension(this.FileUploadControl.PostedFile.FileName);
            if ((!lsFileExtension.Equals(".csv")))
            {
                Session["errorMessage"] = "Invalid file. Please select a .csv file.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            return true;
        }
        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (ImportValidation())
            {
                DataTable dtExcelRecords = new DataTable();
                string fileLocation = Server.MapPath("~/App_Data/");
                if (this.FileUploadControl.HasFile)
                {
                    string fileName = Path.GetFileName(FileUploadControl.PostedFile.FileName);
                    this.FileUploadControl.SaveAs(fileLocation + fileName); // save file to server
                    dtExcelRecords = Utils.AppConstants.ImportCSVFile(fileName, fileLocation);
                }
                DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                DataTable tblRDR1 = (DataTable)Session["INVTable"];
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                foreach (DataRow r in dtExcelRecords.Rows)
                {
                    LoadItem(poDate, ref tblRDR1, dbType, r["ItemCode"].ToString(), r["Quantity"].ToString(), r["DisCount"].ToString(), r["Price"].ToString());
                }

                if (tblRDR1.Rows.Count > 0)
                    foreach (DataRow dr in tblRDR1.Rows)
                        updateRowTotalPrice(dr, "");
                //ReLoad Data
                BindData(tblRDR1);
                updateTableTotalPrice();
            }
        }

        protected void btnGetImportTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                string filePath = Server.MapPath(SupportDocs.fileImportParts);
                string downloadName = "Parts.csv";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadName + "");
                Response.ContentType = "text/csv";
                Response.TransmitFile(filePath);
                Response.End();
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                MasterData obj = new MasterData();
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataTable dtSQ = (DataTable)Session["INVTable"];
                if (dtSQ != null && dtSQ.Rows.Count > 0)
                {
                    Utils.NpoiExport npoiExport = new Utils.NpoiExport(this.Server.MapPath(SupportDocs.pathPartsTemplate + "INV.xls"));
                    npoiExport.GetSheet("INV");
                    //Get Customer Infor
                    DataSet dsCustomer = obj.GetCustomerByCode(dbType, this.txtCustomerCode.Text);

                    // Collection header data
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    DataRow drHeader = dtSQ.Rows[0];
                    dic.Add("paInvoiceNo", "Quyết toán số: " + this.txtInvNo.Text);
                    dic.Add("paSONumber", "Ký hiệu " + this.txtKH.Text);
                    dic.Add("paContactPerson", "Người liện hệ: " + this.txtContactPerson.Text);
                    dic.Add("paSalesMan", "Người viên phụ tùng: " + this.ddlSaleMan.SelectedItem.Text);
                    dic.Add("paCount", dtSQ.Rows.Count);
                    dic.Add("paDeliveryDate","Ngày phát hành : " + Utils.AppConstants.ConvertToDate(this.txtDueDate.Text).ToString(Utils.AppConstants.DATE));
                    dic.Add("paPostingDate", "Ngày đặt hàng : "+Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text).ToString(Utils.AppConstants.DATE));
                    GeneralFunctions GF = new GeneralFunctions();
                    npoiExport.SetValue("paTotalString", GF.Amount2Words(long.Parse(GF.ResetFormatNumeric(this.lblPaymentTotal.Text)), " đồng"));

                    if (dsCustomer != null && dsCustomer.Tables.Count > 0 && dsCustomer.Tables[0].Rows.Count > 0)
                    {
                        dic.Add("paCustomer", "Khách hàng: " + dsCustomer.Tables[0].Rows[0]["CardName"].ToString());
                        dic.Add("paAddress", dsCustomer.Tables[0].Rows[0]["Address"].ToString());
                        dic.Add("paPhone1", "Điện thoại: " + dsCustomer.Tables[0].Rows[0]["Phone1"].ToString());
                        dic.Add("paPhone2", dsCustomer.Tables[0].Rows[0]["Phone2"].ToString());
                        dic.Add("paFax", dsCustomer.Tables[0].Rows[0]["Fax"].ToString());
                        dic.Add("paLicTradNum", "Mã số thuế: " + dsCustomer.Tables[0].Rows[0]["LicTradNum"].ToString());
                    }

                    npoiExport.SetValues(dic);
                    npoiExport.ExportQT(dtSQ, 13, dtSQ.Rows.Count);
                    // Build xls file name
                    string xlsxFileName = "Retail-Sales-Invoice-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + ".xls";
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + xlsxFileName);
                    Response.Clear();
                    Response.BinaryWrite(npoiExport.GetFileHasChanged());
                    Response.End();
                }

            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                lblError.Enabled = true;
            }
        }

        protected void btnPrint1_Click(object sender, EventArgs e)
        {
            try{
               MasterData obj = new MasterData();
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataTable dtSQ = (DataTable)Session["INVTable"];
                if (dtSQ != null && dtSQ.Rows.Count > 0)
                {
                    Utils.NpoiExport npoiExport = new Utils.NpoiExport(this.Server.MapPath(SupportDocs.pathPartsTemplate + "INVENTORYTRANSFERT.xls"));
                    npoiExport.GetSheet("XK");
                    //Get Customer Infor
                    DataSet dsCustomer = obj.GetCustomerByCode(dbType, this.txtCustomerCode.Text);

                    // Collection header data
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    DataRow drHeader = dtSQ.Rows[0];
                    dic.Add("paInvoiceNo", "Quyết toán số: " + this.txtInvNo.Text);
                    dic.Add("paSONumber", "Ký hiệu " + this.txtKH.Text);
                    dic.Add("paContactPerson", "Người liện hệ: " + this.txtContactPerson.Text);
                    dic.Add("paSalesMan", "Người viên phụ tùng: " + this.ddlSaleMan.SelectedItem.Text);
                    dic.Add("paCount", dtSQ.Rows.Count);
                    dic.Add("paDeliveryDate","Ngày phát hành : " + Utils.AppConstants.ConvertToDate(this.txtDueDate.Text).ToString(Utils.AppConstants.DATE));
                    dic.Add("paPostingDate", "Ngày đặt hàng : "+Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text).ToString(Utils.AppConstants.DATE));
                    GeneralFunctions GF = new GeneralFunctions();
                    npoiExport.SetValue("paTotalString", GF.Amount2Words(long.Parse(GF.ResetFormatNumeric(this.lblPaymentTotal.Text)), " đồng"));

                    if (dsCustomer != null && dsCustomer.Tables.Count > 0 && dsCustomer.Tables[0].Rows.Count > 0)
                    {
                        dic.Add("paCustomer", "Khách hàng: " + dsCustomer.Tables[0].Rows[0]["CardName"].ToString());
                        dic.Add("paAddress", dsCustomer.Tables[0].Rows[0]["Address"].ToString());
                        dic.Add("paPhone1", "Điện thoại: " + dsCustomer.Tables[0].Rows[0]["Phone1"].ToString());
                        //dic.Add("paPhone2", dsCustomer.Tables[0].Rows[0]["Phone2"].ToString());
                        dic.Add("paFax", dsCustomer.Tables[0].Rows[0]["Fax"].ToString());
                        dic.Add("paLicTradNum", "Mã số thuế: " + dsCustomer.Tables[0].Rows[0]["LicTradNum"].ToString());
                    }

                    npoiExport.SetValues(dic);
                    npoiExport.ExportXK(dtSQ, 17, dtSQ.Rows.Count);
                    // Build xls file name
                    string xlsxFileName = "Retail-Sales-Invoice" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + ".xls";
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + xlsxFileName);
                    Response.Clear();
                    Response.BinaryWrite(npoiExport.GetFileHasChanged());
                    Response.End();
                }

            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                lblError.Enabled = true;
            }
        }
    }
}